package com.jeesite.modules.task.oa.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.task.oa.dto.OAUserDTO;
import com.jeesite.modules.task.oa.dto.OAUserOfficeDTO;
import com.jeesite.modules.task.oa.dto.OfficeDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;

/**
 * @projectName: whgadc
 * @package: com.jeesite.modules.task.oa.service
 * @className: OAOfficeSyncService
 * @description: TODO
 * @date: 2023/11/28 14:56
 * @version: 1.0
 */
@Service("oaOfficeSyncService")
@Slf4j
public class OAOfficeSyncService {

    @Autowired
    private OfficeService officeService;

    @Autowired
    private EmpUserService empUserService;


    public void officeSync(){
        log.info("office sync==========");
        List<OfficeDTO> officeDTOS = (List<OfficeDTO>) readJson("office");
        if (CollectionUtil.isNotEmpty(officeDTOS)){
            //第一级机构
            officeDTOS.stream().filter(officeDTO -> Objects.equals("1", officeDTO.getORGAN_LEVEL())).forEach(officeDTO -> {
                Office office = new Office();
                office.setOfficeName(officeDTO.getORGAN_NAME());
                office.setFullName(officeDTO.getFULL_NAME());
                office.setViewCode("100000000"+officeDTO.getID());
                office.setOaId(officeDTO.getID());
                office.setTreeNames(officeDTO.getORGAN_NAME());
                office.setParent(null);
                office.setParentCodes(null);
                office.setTreeSort(Integer.parseInt(officeDTO.getSORT_NUM()));
                office.setTreeSorts("00000000"+office.getTreeSort()+",");
                office.setTreeLeaf("0");
                office.setTreeLevel(0);
                office.setOfficeType("0");
                office.setStatus("0");
                office.setCreateBy("system");
                office.setCreateDate(new Date());
                officeService.save(office);
            });

            officeDTOS.stream().filter(officeDTO -> Objects.equals("2", officeDTO.getORGAN_LEVEL())).forEach(officeDTO -> {
                Office office = new Office();
                office.setOfficeName(officeDTO.getORGAN_NAME());
                office.setFullName(officeDTO.getFULL_NAME());
                office.setViewCode("100000000"+officeDTO.getID());
                Office param = new Office();
                param.setViewCode("100000000"+officeDTO.getPARENT_ORG());

                List<Office> parents = officeService.findList(param);
                if (parents.size() > 0){
                    Office parent = parents.get(0);
                    office.setParent(parent);
                    office.setTreeNames(parent.getTreeNames()+"/"+officeDTO.getORGAN_NAME());
                    office.setParentCodes(parent.getOfficeCode()+",");
                    office.setTreeSorts(parent.getTreeSorts()+"00000000"+office.getTreeSort()+",");
                }
                if (StringUtils.isNotBlank(officeDTO.getSORT_NUM())){
                    office.setTreeSort(Integer.parseInt(officeDTO.getSORT_NUM()));
                }else {
                    office.setTreeSort(999);
                }
                office.setOaId(officeDTO.getID());
                office.setTreeLeaf("1");
                office.setTreeLevel(1);
                office.setOfficeType("0");
                office.setStatus("0");
                office.setCreateBy("system");
                office.setCreateDate(new Date());
                officeService.save(office);
            });

            officeDTOS.stream().filter(officeDTO -> Objects.equals("3", officeDTO.getORGAN_LEVEL())).forEach(officeDTO -> {
                Office office = new Office();
                office.setOfficeName(officeDTO.getORGAN_NAME());
                office.setFullName(officeDTO.getFULL_NAME());
                office.setViewCode("100000000"+officeDTO.getID());
                Office param = new Office();
                param.setViewCode("100000000"+officeDTO.getPARENT_ORG());

                List<Office> parents = officeService.findList(param);
                if (parents.size() > 0){
                    Office parent = parents.get(0);
                    office.setParent(parent);
                    office.setTreeNames(parent.getTreeNames()+"/"+officeDTO.getORGAN_NAME());
                    office.setParentCodes(parent.getOfficeCode()+",");
                    office.setTreeSorts(parent.getTreeSorts()+"00000000"+office.getTreeSort()+",");
                }
                if (StringUtils.isNotBlank(officeDTO.getSORT_NUM())){
                    office.setTreeSort(Integer.parseInt(officeDTO.getSORT_NUM()));
                }else {
                    office.setTreeSort(999);
                }
                office.setOaId(officeDTO.getID());
                office.setTreeLeaf("1");
                office.setTreeLevel(2);
                office.setOfficeType("0");
                office.setStatus("0");
                office.setCreateBy("system");
                office.setCreateDate(new Date());
                officeService.save(office);
            });

            officeDTOS.stream().filter(officeDTO -> Objects.equals("4", officeDTO.getORGAN_LEVEL())).forEach(officeDTO -> {
                Office office = new Office();
                office.setOfficeName(officeDTO.getORGAN_NAME());
                office.setFullName(officeDTO.getFULL_NAME());
                office.setViewCode("100000000"+officeDTO.getID());
                Office param = new Office();
                param.setViewCode("100000000"+officeDTO.getPARENT_ORG());

                List<Office> parents = officeService.findList(param);
                if (parents.size() > 0){
                    Office parent = parents.get(0);
                    office.setParent(parent);
                    office.setTreeNames(parent.getTreeNames()+"/"+officeDTO.getORGAN_NAME());
                    office.setParentCodes(parent.getOfficeCode()+",");
                    office.setTreeSorts(parent.getTreeSorts()+"00000000"+office.getTreeSort()+",");
                }
                if (StringUtils.isNotBlank(officeDTO.getSORT_NUM())){
                    office.setTreeSort(Integer.parseInt(officeDTO.getSORT_NUM()));
                }else {
                    office.setTreeSort(999);
                }
                office.setOaId(officeDTO.getID());
                office.setTreeLeaf("1");
                office.setTreeLevel(3);
                office.setOfficeType("0");
                office.setStatus("0");
                office.setCreateBy("system");
                office.setCreateDate(new Date());
                officeService.save(office);
            });
        }
    }

    public void userSync(){
        log.info("office sync==========");
        List<OAUserDTO> userDTOS = (List<OAUserDTO>) readJson("user");
        if (CollectionUtil.isNotEmpty(userDTOS)){
            userDTOS.stream().forEach(oaUserDTO -> {
                /*addUser(oaUserDTO);*/
                if (getLocalUser(oaUserDTO) == null){
                    addUser(oaUserDTO);
                }
            });
        }
    }

    private Object readJson(String type){
        try {
            File file;
            if (Objects.equals("office",type)){
                file = new File("/usr/office.json");
            }else {
                file = new File("/usr/local/tomcat/user.json");
            }
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String line;
            StringBuilder jsonBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                jsonBuilder.append(line);
            }

            bufferedReader.close();
            inputStreamReader.close();
            fileInputStream.close();

            String json = jsonBuilder.toString();
            // 打印读取到的JSON内容
            //System.out.println(json);
            JSONObject jsonObject = JSONObject.parseObject(json);
            if (Objects.equals("office",type)){
                return JSONArray.parseArray(jsonObject.getString("organList"), OfficeDTO.class);
            }else {
                return JSONArray.parseArray(jsonObject.getString("userList"), OAUserDTO.class);
            }

        } catch (Exception e) {
            log.error("读取用户、机构json出错",e);
        }

        return null;
    }

    /**
     *
     * @param commonDTO:
     * @return void
     * @version V1.0.0
     * @Description: 用户增量更新（接受增量用户数据，新增、删除用户）
     * @date 16:51 2024/1/3
     */
    public void syncUpdateUsers(OAUserOfficeDTO commonDTO){
        if (commonDTO != null && commonDTO.getUserList() != null){
            List<OAUserDTO> userDTOS = commonDTO.getUserList();
            //新增用户
            userDTOS.stream().filter(oaUserDTO -> Objects.equals("1",oaUserDTO.getCZBZ())).forEach(oaUserDTO -> {
                if (getLocalUser(oaUserDTO) == null){
                    addUser(oaUserDTO);
                }
            });

            //删除用户
            userDTOS.stream().filter(oaUserDTO -> Objects.equals("3",oaUserDTO.getCZBZ())).forEach(oaUserDTO -> {
                delUser(oaUserDTO);
            });
        }

    }

    /**
     *
     * @param commonDTO:
     * @return void
     * @version V1.0.0
     * @Description: 用户全量（接受全量数据，只新增本地不存在的用户）
     * @date 16:52 2024/1/3
     */
    public void syncAllUsers(OAUserOfficeDTO commonDTO){
        if (commonDTO != null && commonDTO.getUserList() != null){
            List<OAUserDTO> userDTOS = commonDTO.getUserList();
            userDTOS.stream().forEach(oaUserDTO -> {
                if (getLocalUser(oaUserDTO) == null){
                    addUser(oaUserDTO);
                }
            });
        }

    }

    private EmpUser getLocalUser(OAUserDTO oaUserDTO){
        EmpUser temp = new EmpUser();
        temp.setLoginCode(oaUserDTO.getLOGIN_NAME());
        List<EmpUser> localUsers = empUserService.findList(temp);
        if (CollectionUtil.isNotEmpty(localUsers)){
            return localUsers.get(0);
        }

        return null;
    }

    private void addUser(OAUserDTO oaUserDTO){
        EmpUser user = new EmpUser();
        user.setLoginCode(oaUserDTO.getLOGIN_NAME());
        user.setUserName(oaUserDTO.getUSER_NAME());
        user.setMobile(oaUserDTO.getSJHM());
        user.setSex(oaUserDTO.getSEX());
        user.setPassword("11");
        Employee employee = new Employee();
        employee.setEmpName(user.getUserName());
        employee.setEmpNo(user.getLoginCode());

        Office param = new Office();
        param.setViewCode("100000000"+oaUserDTO.getDEFAULT_ORGAN_ID());
        List<Office> offices = officeService.findList(param);
        if (CollectionUtil.isNotEmpty(offices)){
            Office local = offices.get(0);
            if (StringUtils.isBlank(local.getOfficeCode())){
                log.error("office 为空,{}",oaUserDTO);
            }else {
                employee.setOffice(local);

                user.setEmployee(employee);
                user.setRefName(user.getUserName());
                if(StringUtils.isNotBlank(oaUserDTO.getSORT())){
                    user.setUserWeight(Integer.parseInt(oaUserDTO.getSORT()));
                }else {
                    user.setUserWeight(999);
                }

                user.setStatus("0");
                user.setCreateBy("system");
                user.setCreateDate(new Date());
                empUserService.save(user);

                log.info("新增用户,{}",oaUserDTO.getUSER_NAME());
            }

        }
    }

    private void delUser(OAUserDTO oaUserDTO){
        EmpUser localUser = getLocalUser(oaUserDTO);
        if (localUser != null) empUserService.delete(localUser);
    }
}
